package gui.nodes;

import gui.AbstractViewPane;
import gui.MainController;
import gui.SemestreUIConsulter;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.tree.DefaultMutableTreeNode;

import utility.Record;
import business.SemestreBL;

public class SemestreNode extends AbstractNode {

	int semestreId;
	int anneeEtudeId;
	String semestreName;
	DefaultMutableTreeNode semestreNode;
	private SemestreRoot parentNode;

	public SemestreNode(SemestreRoot parentNode, Record semestreRec, int anneeEtudeId) {
		super();
		this.parentNode = parentNode;
		this.semestreId = semestreRec.getId();
		this.anneeEtudeId = anneeEtudeId;
		this.semestreName = semestreRec.getLibelle();
	}

	@Override
	public JPopupMenu makePopup() {
		return new Popup();
	}

	@Override
	public String getNodeName() {
		return semestreName;
	}

	public void loadPrimaryViewPane() {
		AbstractViewPane newViewPane = new SemestreUIConsulter(parentNode, AbstractViewPane.ViewMode.CONSULTATION, semestreId,
				anneeEtudeId);
		MainController.getInstance().setViewPane(newViewPane);
	}

	public void loadModifierViewPane() {
		AbstractViewPane newViewPane = new SemestreUIConsulter(parentNode,
				AbstractViewPane.ViewMode.MODIFICATION, semestreId,
				anneeEtudeId);
		MainController.getInstance().setViewPane(newViewPane);
	}

	public void loadSupprimerViewPane() {
		if (supprimer() == JOptionPane.YES_OPTION) {
			SemestreBL semBL = new SemestreBL(semestreId);
			semBL.supprimerSemestre();
		}
		((AbstractNode)parent).refresh();
	}

	private class Popup extends JPopupMenu implements ActionListener {
		JMenuItem modifier = new JMenuItem("Modifier un semestre");
		JMenuItem supprimer = new JMenuItem("Supprimer un semestre");

		public Popup() {

			modifier.addActionListener(this);
			supprimer.addActionListener(this);

			add(modifier);
			add(supprimer);
		}

		public void actionPerformed(ActionEvent e) {
			if (e.getSource() == modifier) {
				loadModifierViewPane();
			}
			if (e.getSource() == supprimer) {
				loadSupprimerViewPane();
			}

		}

	}

	@Override
	public void expandHook() {
		this.removeAllChildren();
		
		UERoot ueRootNode = new UERoot(this, this.semestreId);
		add(ueRootNode);

		GroupeRoot goupeRootNode = new GroupeRoot(this.semestreId);
		add(goupeRootNode);
	}
	
	public int supprimer() {
		return JOptionPane.showConfirmDialog(
			    null,
			    "Êtes vous sûr de vouloir supprimer le semestre\n"+
			    //ensBL.getName()+" "+ensBL.getPrenom()+
			    " ?",
			    "Avertissement",
			    JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
		
	}

}
